<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>  
  <div class="business_map" v-loading="loading">
    <div class="business-map__title">
      <div class="title">业务地图配置</div>
      <div class="option_btn">
        <el-button size="small" type="primary" @click="saveData">保存</el-button>
        <el-button size="small" @click="cancel">返回</el-button>
      </div>
    </div>
    <div class="business-map__content">
      <div class="left" v-if="!props.isView">
        <h4>要素库模型</h4>
        <div class="left-wrapper">
          <div class="database_item" v-for="item in databases" :id="item.modelId" :key="item" draggable="true" @dragstart="dragStart" @dragend="dragEnd">
            <img :src="dataBaseImg" alt="" />
            <el-tooltip :content="item.modelName" placement="top">
              <div class="database_name" :title="item.modelName">{{ item.modelName }}</div>
            </el-tooltip>
            <!-- <div class="database_name" :title="item.modelName">{{ item.modelName }}</div> -->
          </div>
        </div>
      </div>
      <div class="right" :class="{ 'isView': props.isView }">
        <div :class="['card_item', 'bg-'+index]" v-for="(item, index) in cards" :key="item">
          <div class="close" v-if="!props.isView">
            <el-icon :color="setColor(index)" @click="deleteCard(item)"><CircleClose /></el-icon>
          </div>
          <div class="title">
            <div>{{ index + 1 }}</div>
            <el-tooltip :content="item.name" placement="top">
              <div>{{ item.name }}</div>
            </el-tooltip>
            <div v-if="!props.isView">
              <el-icon @click="modifyName(item)"><EditPen /></el-icon>
            </div>
          </div>
          <div class="content" @dragover="dragOver" @drop="drop" :id="item.index">
            <div draggable="true" @dragstart="dragStart" :class="['database_item', 'border-'+index]" :dataSet="index+'-'+cIndex" v-for="(el, cIndex) in item.databases" :id="el.modelId + '-' + index + '-' + cIndex" :key="el">
              <div draggable="false" class="close" v-if="!props.isView">
                <el-icon color="#a3a3a3" @click="deleteDataBase(item, el, index, cIndex)"><CircleClose /></el-icon>
              </div>
              <img draggable="false" :src="dataBaseImg" alt="" />
              <div draggable="false" class="database_name">
                <a @click="showDataBaseInfo(el)">{{ el?.modelName }}</a>
              </div>
            </div>
          </div>
        </div>
        <div class="plus" v-if="!props.isView">
          <img :src="plus" alt="" @click="addCard" />
        </div>
      </div>
    </div>
    <el-dialog title="步骤名称修改" v-model="visible">
      <el-form size="small">
        <el-form-item label="步骤名称：">
          <el-input v-model="formData.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="cancel()">取消</el-button>
          <el-button size="small" type="primary" @click="submit"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <DataBaseView v-if="dataBaseVisible" :dataBaseVisible="dataBaseVisible" :data="currentDataBase" @handleEvent="handleEvent" />
  </div>
</template>
<script name="BusinessMap" setup>
import DataBaseView from './DataBaseView.vue';
import dataBaseImg from '@/assets/images/database.svg';
import plus from '@/assets/images/plus-square-fill.svg';
import { getDataBaseList, addBusinessSceneMap, getBusinessSceneMapDetail, getBusinessSceneMapList, getModelList } from '@/api/metaData/index';
const emit = defineEmits(['handleData', 'handleEvent']);
const props = defineProps(['isView', 'rowData']);
//左侧库列表
const dragTargetId = ref('');
const visible = ref(false);
const formData = ref({ name: '', index: '' });
const dataBaseVisible = ref(false);
const currentDataBase = ref(null);
const databases = ref([]);
const loading = ref(false);
const cards = ref([{ name: '步骤1', index: 1, databases: [] }]);
const handleEvent = () => {
  currentDataBase.value = null;
  dataBaseVisible.value = false;
};
// icon-color del btn
const setColor = (index) => {
  let target = index % 9;
  const colorMap = {
    0: "#cdae2c",
    1: "#e6854e",
    2: "#ef80a2",
    3: "#d851c7",
    4: "#5038c7",
    5: "#1c647f", 
    6: "#1ca66a",
    7: "#8eb93d",
    8: "#cdae2c",
  }
  return colorMap[target];
}
// 保存业务地图
const saveData = () => {
  let validate = true;
  let cardName = '';
  if (cards.value.length > 0) {
    cards.value.forEach((el) => {
      if (el?.databases.length === 0) {
        validate = false;
        cardName = el?.name;
      }
    });
  } else {
    ElMessage({ showClose: true, message: `请配置场景地图！`, type: 'warning' });
    return;
  }
  if (!validate) {
    ElMessage({ showClose: true, message: `${cardName} 需至少选择一个库类型！`, type: 'warning' });
    return;
  }
  loading.value = true;
  const cardDataList = [];
  cards.value.forEach((el) => {
    if (el.databases.length > 0) {
      el.databases.forEach((item) => {
        cardDataList.push({ 
          modelId: item.modelId,
          businessScenarioId: props?.rowData?.id,
          businessScenario: item.businessScenario,
          systemName: item.businessSystem || item.systemName,
          sceneDescription: props?.rowData?.sceneDescription,
          stepDescription: el?.name, 
          stepRank: el.index,
          elementLibraryType: item.databaseType || item.elementLibraryType,
          subType: item.databaseSubtype,
          modelName: item.modelName,
        });
      });
    }
  });
  addBusinessSceneMap(cardDataList)
    .then((res) => {
      if (res.code === 200) {
        ElMessage({ showClose: true, message: '保存成功！', type: 'success' });
        emit('handleEvent', { component: 'addBusines', row: null });
      }
    })
    .finally(() => {
      loading.value = false;
    });
};  
const cancel = () => {
  cards.value = [{ name: '步骤1', index: 1, databases: [] }]
  emit('handleEvent', { component: 'addBusines', row: null });
}
//初始化数据
// if (props?.mapData) {
//   cards.value = [...props?.mapData];
// }
//展示库类型详情
const showDataBaseInfo = (dataBase) => {
  currentDataBase.value = dataBase;
  dataBaseVisible.value = true;
};
const dragStart = (event) => {
  console.log('dragStart', event)
  dragTargetId.value = event.target.id;
};
const dragEnd = (event) => {
  // 恢复拖拽元素的默认样式
  event.target.style.opacity = '1';
};
const dragOver = (event) => {
  event.preventDefault();
};
const drop = (event) => {
  // 阻止浏览器默认操作
  console.log('drop', event)
  // const toElementStepId = event.toElement.id;
  const dropElementId = event.target.id.split('-')[0];
  event.preventDefault();
  // 获取被拖动的元素数据
  const id = event.target.id;
  const databaseItem = databases.value.filter((item) => {
    return item.modelId == dragTargetId.value.split('-')[0];
  });
  console.log('databaseItem', databaseItem)
  cards.value.forEach((card) => {
    if (card.index == id) {
      const itemDataBase = card.databases || [];
      let hasBase = false;
      if (itemDataBase.length > 0) {
        itemDataBase.forEach((el) => {
          if (el?.modelId == dragTargetId.value.split('-')[0]) {
            hasBase = true;
          }
        });
      }
      if (hasBase) {
        ElMessage({ showClose: true, message: '已存在相同的库类型，请重新选择！', type: 'warning' });
        return;
      } else {
        card.databases.push(databaseItem[0]);
      }
    }
  });
  emit('handleData', { data: cards.value });
};
//增加卡片步骤
const addCard = () => {
  const ids = cards.value.map((card) => {
    return card.index;
  });
  const maxId = Math.max(...ids);
  cards.value.push({ name: '默认步骤', index: maxId + 1, databases: [] });
  emit('handleData', { data: cards.value });
};
// 删除卡片
const deleteCard = (card) => {
  if (cards.value.length === 1) {
    ElMessage({ showClose: true, message: '场景需至少保留一个步骤！', type: 'warning' });
    return;
  }
  ElMessageBox.confirm('是否确认删除此步骤？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cards.value = cards.value.filter((el) => {
      return el.index != card.index;
    });
    cards.value.forEach((el) => {
      if (el.index > card.index) {
        el.index--;
      }
    });
  });
  emit('handleData', { data: cards.value });
};
// 删除库类型
const deleteDataBase = (card, dataBase, index, cIndex) => {
  cards.value[index].databases.splice(cIndex, 1);
  // ElMessageBox.confirm('是否确认删除此库类型？', '提示', {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消',
  //   type: 'warning'
  // }).then(() => {
  //   cards.value[index].databases.splice(cIndex, 1)
  //   // cards.value.forEach((el) => {
  //   //   if (el.index == card.index) {
  //   //     if (el.databases.length > 0) {
  //   //       el.databases = el.databases.filter((item) => {
  //   //         return item.index != dataBase.index;
  //   //       });
  //   //     }
  //   //   }
  //   // });
  // });
  emit('handleData', { data: cards.value });
};
//修改卡片名称
const modifyName = (data) => {
  visible.value = true;
  formData.value.name = data.name;
  formData.value.index = data.index;
};
// 提交修改
const submit = () => {
  cards.value.forEach((el) => {
    if (el.index == formData.value.index) {
      el.name = formData.value.name;
    }
  });
  visible.value = false;
  emit('handleData', { data: cards.value });
};
// 业务地图配置详情
const getSceneMapDetail = (param) => {
  getBusinessSceneMapList(param).then((res) => {
    if (res.code === 200) {
      // const cards = ref([{ name: '步骤1', index: 1, databases: [] }]);
      if (res?.rows.length == 0) {
        return;
      }
      cards.value = [];
      const stepArr = [...new Set(res.rows.map(item => item.stepRank))];
      stepArr.forEach((step) => {
        const stepData = res.rows.filter(item => item.stepRank === step);
        const card = { name: `步骤${step}`, index: step, databases: stepData };
        // stepData.forEach((item) => {
        //   const dataBase = databases.value.filter(db => db.id === item.elementLibraryType);
        //   if (dataBase.length > 0) {
        //     card.databases.push(dataBase[0]);
        //   }
        // });
        cards.value.push(card);
      });
    }                                                   
  });                                                      
}
onMounted(async () => {
  if (!props.isView) {
    // getDataBaseList({ pageNum: 1, pageSize: 100, isAsc: 'descending' }).then((res) => {
    //   databases.value = res.rows || [];
    // });props?.rowData?.sceneName
    // getModelList({businessScenario: props?.rowData?.sceneName, businessSystem: props?.rowData?.systemName}).then((res) => {
    //   databases.value = res.data || [];
    //   databases.value.forEach((item) => {  
    //     item.modelId = item.fieldList[0].id;     
    //   })
    // });
    let option1 = await getModelList({businessScenario: props?.rowData?.sceneName, businessSystem: '通用'});
    let option2 = await getModelList({businessScenario: props?.rowData?.sceneName, businessSystem: props?.rowData?.systemName});
    Promise.all([option1, option2]).then((res) => { 
      let option = (res[0]?.data || []).concat(res[1]?.data || []);
      databases.value = option;
      databases.value.forEach((item) => {
        item.modelId = item.id;     
      })
    });
  }
  props?.rowData?.id && getSceneMapDetail({businessScenarioId: props?.rowData?.id});
});
</script>
<style lang="scss" scoped>
.business_map {
  height: 100%;
  .business-map__title {
    height: 60px;
    line-height: 60px;
    padding: 0 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: rgba(65,143,247,.4);
    .title {
      background: #fff;
      color: #004ea2;
      /* padding: 10px 20px; */
      /* border-radius: 5px; */
      font-weight: 700;
      font-size: 16px;
      height: 50px;
      line-height: 50px;
      margin-top: 20px;
      padding: 0 10px;
      border-top-left-radius: 5px;
      border-top-right-radius: 5px;
    }
  }
  .business-map__content {
    height: calc(100% - 60px);
    width: 100%;
    display: flex;
    justify-content: space-between;
    user-select: none;
    padding: 20px 20px 20px 20px;
  }
  .left {
    width: 240px;
    height: 100%;
    // overflow: auto;
    // display: flex;
    // flex-wrap: wrap;
    border: 1px solid #d9d9d9;
    box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
    // align-content: baseline;
    h4 {
      text-align: center;
    }
    .left-wrapper {
      width: 240px;
      height: 100%;
      overflow: auto;
      display: flex;
      flex-wrap: wrap;
      // border: 1px solid #d9d9d9;
      align-content: baseline;
    }
    .database_item {
      height: 60px;
      width: 60px;
      display: flex;
      flex-direction: column;
      align-items: center;
      border: 1px solid #d9d9d9;
      justify-content: center;
      margin: 8px;
      border-radius: 4px;
      > img {
        height: 32%;
        width: 32px;
        pointer-events: none;
      }
      .database_name {
        font-size: 12px;
        margin-top: 6px;
        pointer-events: none;
        width: 100%;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        cursor: move;
        text-align: center;
      }
    }
  }
  .right {
    height: 100%;
    width: calc(100% - 250px);
    border: 1px solid #d9d9d9;
    padding: 10px;
    display: flex;
    overflow-x: auto;
    box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
    .card_item {
      height: 100%;
      min-width: 120px;
      margin-right: 10px;
      border: 1px solid #d9d9d9;
      background: #fcf8e9;
      border-radius: 8px;
      position: relative;
      &.bg-0 {
        border: 1px solid #cdae2c;
        background: #fcf8e9;
      }
      &.bg-1 {
        border: 1px solid #e6854e;
        background: #faefe9;
      }
      &.bg-2 {
        border: 1px solid #ef80a2;
        background: #fcf1f4;
      }
      &.bg-3 {
        border: 1px solid #d851c7;
        background: #f7eef6;
      }
      &.bg-4 {
        border: 1px solid #5038c7;
        background: #f3f0ff;
      }
      &.bg-5 {
        border: 1px solid #1c647f;
        background: #eaf3f6;
      }
      &.bg-6 {
        border: 1px solid #1ca66a;
        background: #ecf7f2;
      }
      &.bg-7 {
        border: 1px solid #8eb93d;
        background: #f3f7eb;
      }
      &.bg-8 {
        border: 1px solid #cdae2c;
        background: #fcf8e9;
      }
      .close {
        position: absolute;
        right: 2px;
        top: 2px;
        cursor: pointer;
      }
      .title {
        width: 100%;
        height: 40px;
        display: flex;
        font-size: 12px;
        align-items: center;
        justify-content: center;
        > div:nth-child(1) {
          height: 20px;
          width: 20px;
          border: 1px solid #d9d9d9;
          border-radius: 4px;
          text-align: center;
          line-height: 20px;
        }
        > div:nth-child(2) {
          margin-left: 4px;
          max-width: 50px;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
        }
        > div:nth-child(3) {
          margin-left: 4px;
          height: 20px;
          width: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
        }
      }
      .content {
        height: calc(100% - 50px);
        background: #fff;
        margin: 0 10px 10px 10px;
        display: flex;
        flex-direction: column;
        align-items: center;
        overflow: auto;
        .database_item {
          height: 60px;
          // width: 60px;
          width: calc(100% - 16px);
          display: flex;
          flex-direction: column;
          align-items: center;
          border: 1px solid #d9d9d9;
          justify-content: center;
          margin: 8px;
          border-radius: 4px;
          position: relative;
          > img {
            height: 32%;
            width: 32px;
          }
          .database_name {
            font-size: 12px;
            margin-top: 6px;
            width: 100%;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            text-align: center;
          }
          .database_name:hover {
            text-decoration-line: underline;
            color: #409eff;
          }
          .close {
            position: absolute;
            right: 2px;
            top: 2px;
            cursor: pointer;
          }
        }
      }
    }
    .plus {
      height: 100%;
      display: flex;
      align-items: center;
      margin-left: 20px;
      > img {
        height: 60px;
        width: 60px;
        cursor: pointer;
      }
    }
  }
  .isView {
    width: 100%;
  }
  :deep(.el-link__inner) {
    font-size: 12px;
  }
}
</style>
